In [49]:
# This program displays a rectangular pattern of asterisks
width = 2
height = 2
for h in range(height):
for w in range(width):
print ("*"),
print("")
In [52]:
# This program displays a triangle pattern of asterisks
# *
# * *
# * * *
height = 10
for h in range(height):
for w in range(h + 1):
print ("*"),
print("")
In [62]:
height = 10
for h in range(height):
print ("*" * (h + 1))
In [63]:
"Hello, I wish to register a complaint."[0] # This should be H
Out[63]:
In [67]:
opening = "Hello, I wish to register a complaint."
opening[37]
Out[67]:
In [65]:
len("Hello, I wish to register a complaint.")
Out[65]:
In [66]:
"Hello, I wish to register a complaint."[37]
Out[66]:
In [68]:
"Hello, I wish to register a complaint."[-1] # This should be .
Out[68]:
In [70]:
"Hello, I wish to register a complaint."[-15]
Out[70]:
In [72]:
opening = "Hello, I wish to register a complaint."
opening[-38]
Out[72]:
IndexError
exception is thrown when you use an array index is out of rangeAn Exception is an object or data structure that is passed back to a calling context when there is a problem
If you don't want an exception to cause your program to crash, you can handle them in your code using try/except blocks
try:
statement
statement
except ExceptionName:
statement
statement
Inside the try block are the statement that might throw an exception.
The statements in the except block are run when an exception of type ExceptionName is thrown by the try block.
We'll come back to this later in the course.
In [74]:
opening = "Hello, I wish to register a complaint."
try:
opening[100]
except IndexError:
print("Index out of range for string")
In [78]:
user_input = raw_input("> ")
try:
user_input = int(user_input)
except ValueError:
print("Can't do it. Not a number")
#user_input += 1
#print(user_input)
In [79]:
name = "Monty"
for character in name:
print(character)
In [81]:
name ="Monty"
index = 0
while index < len(name):
print(name[index])
index += 1
In [ ]:
name ="Monty"
index = 0
while index < 6:
print(name[index])
index += 1
In [86]:
"Hello, I wish to register a complaint."[10:20:2]
Out[86]:
In [87]:
knights = "Arthur Lancelot Robin Bedevere Galahad"
if "Arthur" in knights:
print("Arthur is a knight")
else:
print("Arthur is not a knight")
if "Graham" not in knights:
print("Graham is not a knight")
else:
print("Graham is a knight")
In [91]:
"Hello, I wish to register a complaint.".isdigit()
Out[91]:
In [ ]:
# Write a function to check that a password is strong enough
In [93]:
"Hello, I wish to register a complaint.".upper()
Out[93]:
In [ ]:
knights = "Lancelot"
knights += " Robin"
knights
In [ ]:
In [94]:
"Hello, I wish to register a complaint.".find("wish")
Out[94]:
In [97]:
"Hello, I wish to register a complaint."[9:13]
Out[97]:
In [99]:
"Hello, I wish to register a complaint.".replace("wish", "demand")
Out[99]:
In [100]:
knight_string = "Arthur Lancelot Robin Bedevere Galahad"
knight_list = knight_string.split()
knight_list
Out[100]:
In [102]:
date_string = "15/10/2015"
date_string.split("/")
Out[102]:
def function_name():
statement
statement
statement
Functions are either a void function or a value-returning function.
In [104]:
# This program demonstrates a function
# First we define a function named "message"
def message():
print("I am Arthur")
print ("King of the Britons")
# Call the message function
message()
See the visualization
In [105]:
def wrapped_message():
print("I have a message for you")
message()
print("Good bye!")
def message():
print("I am Arthur")
print ("King of the Britons")
wrapped_message()
The visibility or scope of a variable is what allows us to have variables that have the same name, but point to different data in different contexts.
In [107]:
def blue_jays():
runs = 6
print ("The Blue Jays scored {0} runs").format(runs)
rangers()
def rangers():
runs = 3
print("The Rangers scored " + str(runs) + " runs")
runs = 9
print(runs)
blue_jays()
print(runs)
print(runs)
In [108]:
def greet(name):
# This printing style is legal in Python 2, but
# discouraged in Python 3
print("Hello %s!") % name
knight = "Sir Bedevere"
greet(knight)
In [110]:
def outrank(knight1, knight2):
print(knight1 + " outranks " + knight2)
outrank("Arthur", "Galahad")
In [111]:
def change_me(arg):
print("change_me() is changing the value")
arg = 0
print("Now the value is {0}").format(arg)
value = "Lancelot"
print("The value is " + value)
change_me(value)
print("Back in main the value is " + value)
In [114]:
def holy_hand_grenade(tick):
output = ""
if tick == 1:
output = "Keepest going"
elif tick == 2:
output = "Nor either count thou two, excepting that thou then proceed to three"
elif tick == 3:
output = "Lobbest thou thy Holy Hand Grenade of Antioch towards thou foe"
elif tick == 4:
output = "Four shalt thou not count"
elif tick == 5:
output = "Five is right out"
return output
instruction = holy_hand_grenade(3)
print(instruction[5:10])
In [ ]:
In [120]:
# Turn this code into a function
def what_to_wear(temperature):
output = ""
if (temperature < 15):
output = "Wear a coat."
return output
what_to_wear(8)
Out[120]:
In [ ]:
# Write a function to sum two values
def sum(number1, number2):